package com.tcoiss.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcoiss.app.domain.GdAdminDivision;
import com.tcoiss.app.mapper.GdAdminDivisionMapper;
import com.tcoiss.app.service.IGdAdminDivisionService;
import com.tcoiss.common.core.enums.ErroEnums;
import com.tcoiss.common.core.exception.CustomException;
import com.tcoiss.common.core.utils.StringUtils;
import com.tcoiss.common.component.service.ApiHelperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GdAdminDivisionServiceImpl extends ServiceImpl<GdAdminDivisionMapper, GdAdminDivision> implements IGdAdminDivisionService {
    @Autowired
    private ApiHelperService apiHelperService;

    @Override
    public List<GdAdminDivision> getList(GdAdminDivision adminDivision) {
        LambdaQueryWrapper<GdAdminDivision> lqw = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank(adminDivision.getName())){
            lqw.like(GdAdminDivision::getName,adminDivision.getName());
        }
        if(StringUtils.isNotBlank(adminDivision.getNumber())){
            lqw.eq(GdAdminDivision::getNumber,adminDivision.getNumber());
        }
        if(adminDivision.getId()!=null&&adminDivision.getId()!=0){
            lqw.eq(GdAdminDivision::getId,adminDivision.getId());
        }
        if(adminDivision.getAdministrativeLevelsId()!=null&&adminDivision.getAdministrativeLevelsId()!=0){
            lqw.eq(GdAdminDivision::getAdministrativeLevelsId,adminDivision.getAdministrativeLevelsId());
        }
        if(StringUtils.isNotBlank(adminDivision.getFullName())){
            lqw.like(GdAdminDivision::getFullName,adminDivision.getFullName());
        }
        if(StringUtils.isNotBlank(adminDivision.getEnable())){
            lqw.notIn(GdAdminDivision::getEnable,adminDivision.getEnable());
        }
        lqw.eq(GdAdminDivision::getStatus,"C");
        return list(lqw);
    }

    @Override
    public String getLastFullName(String lastNumber) {
        LambdaQueryWrapper<GdAdminDivision> lqw = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank(lastNumber)){
            lqw.eq(GdAdminDivision::getNumber,lastNumber);
        }
        List<GdAdminDivision> gdAdminDivisions = list(lqw);
        return gdAdminDivisions.get(0).getFullName();
    }

    @Override
    public boolean initData() {
        //清空历史数据
        LambdaQueryWrapper<GdAdminDivision> lqw = Wrappers.lambdaQuery();
        this.remove(lqw );
        List<GdAdminDivision> gdAdminDivisions =  getDistrictInfo();
        if(gdAdminDivisions!=null){
            return this.saveBatch(gdAdminDivisions);
        }
        return false;
    }

    public List<Map<String, Object>> queryAdminDivision(){

        Map<String, Object> map = new HashMap<>();
        try {
            map.put("keywords", URLEncoder.encode("江西省", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new CustomException(ErroEnums.SYSERRO.getCode(), "系统异常",e);
        }
        map.put("subdistrict", 3);
        map.put("extensions", "base");
        map.put("key", "fc192adf62dc818ffe64fbcc68dfadd1");
        // 请求行政区划获取第四级地址与名称
        Map<String, Object> resultMap = apiHelperService.executeApi("getDistrictInfo", map);
        if (resultMap == null) {
            throw new CustomException(ErroEnums.APIERRO.getCode(),null,ErroEnums.COMERRO.getInfo() + "获取地址坐标请求连接异常");
        } else {
            //成功
            if (Integer.parseInt(resultMap.get("status").toString()) == 1) {
                //redisService.setCacheList("gaode", excelVos);
                return (List<Map<String, Object>>)resultMap.get("districts");
            }
        }
        return null;
    }

    public List<GdAdminDivision> getDistrictInfo() {
        List<Map<String, Object>> province = queryAdminDivision();
        // 获取江西省
        if(province!=null){
            List<GdAdminDivision> gdAdminDivisions = new ArrayList<>();
            for (int i = 0; i < province.size(); i++) {
                Map<String, Object> provinceCode = province.get(0);
                GdAdminDivision gdProvince = new GdAdminDivision();
                gdProvince.setNumber((String) provinceCode.get("adcode"));
                gdProvince.setName((String) province.get(i).get("name"));
                gdProvince.setAdministrativeLevelsId(1L);
                gdProvince.setIsCity("true");
                gdProvince.setFullName(province.get(i).get("name").toString());
                gdProvince.setStatus("C");
                gdProvince.setEnable("1");
                gdAdminDivisions.add(gdProvince);
                // 获取所有市级
                List<Map<String, Object>> city = (List<Map<String, Object>>) province.get(i).get("districts");
                for (int j = 0; j < city.size(); j++) {
                    GdAdminDivision gdCity = new GdAdminDivision();
                    gdCity.setNumber((String) city.get(j).get("city"));
                    gdCity.setName((String) city.get(j).get("name"));
                    gdCity.setAdministrativeLevelsId(2L);
                    gdCity.setParent(gdProvince.getNumber());
                    gdCity.setIsCity("true");
                    gdCity.setFullName(gdProvince.getName()+"_"+city.get(j).get("name").toString());
                    gdCity.setStatus("C");
                    gdCity.setEnable("1");
                    gdAdminDivisions.add(gdCity);
                    // 获取当前市的区县
                    List<Map<String, Object>> district = (List<Map<String, Object>>) city.get(j).get("districts");
                    for (int k = 0; k < district.size(); k++) {
                        GdAdminDivision gdDistrict = new GdAdminDivision();
                        gdDistrict.setNumber((String) district.get(k).get("adcode"));
                        gdDistrict.setName((String) district.get(k).get("name"));
                        gdDistrict.setParent(gdCity.getNumber());
                        gdDistrict.setAdministrativeLevelsId(3L);
                        gdDistrict.setIsCity("true");
                        gdDistrict.setFullName(gdCity.getFullName()+"_"+district.get(k).get("name").toString());
                        gdDistrict.setStatus("C");
                        gdDistrict.setEnable("1");
                        gdAdminDivisions.add(gdDistrict);
                        // 获取当前区县的乡镇
                        List<Map<String, Object>> towns = (List<Map<String, Object>>) district.get(k).get("districts");
                        for(Map<String, Object> town:towns){
                            GdAdminDivision gdTown = new GdAdminDivision();
                            gdTown.setNumber("");
                            gdTown.setName((String) town.get("name"));
                            gdTown.setAdministrativeLevelsId(4L);
                            gdTown.setParent(gdDistrict.getNumber());
                            gdTown.setIsCity("true");
                            gdTown.setFullName(gdDistrict.getFullName()+"_"+town.get("name").toString());
                            gdTown.setStatus("C");
                            gdTown.setEnable("1");
                            gdAdminDivisions.add(gdTown);
                        }
                    }
                }
            }
            return gdAdminDivisions;
        }

        return null;
    }
}
